package com.hengxinguotong.zhihuichengjian.ui.statistics.environment;

import android.app.AlertDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.charts.PieChart;
import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.bean.EnvironmentFormDataStatistics;
import com.hengxinguotong.zhihuichengjian.bean.EnvironmentFormDataStatisticsRes;
import com.hengxinguotong.zhihuichengjian.ui.BaseActivity;
import com.hengxinguotong.zhihuichengjian.utils.BarChartManager;
import com.hengxinguotong.zhihuichengjian.utils.Constants;
import com.hengxinguotong.zhihuichengjian.utils.LineChartManager;
import com.hengxinguotong.zhihuichengjian.utils.PieChartManager;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.weekpicker.MonthPickerDialog;
import com.hengxinguotong.zhihuichengjian.weekpicker.WeekPickerDialog;
import com.hengxinguotong.zhihuichengjian.weekpicker.entity.Month;
import com.hengxinguotong.zhihuichengjian.weekpicker.entity.Week;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @CopyRight 恒信国通信息科技
 * @Author WuLei
 * @Date 2019/3/28
 * <p>
 * 环境报表
 */

public class EnvironmentFormDataActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener {
    @BindView(R.id.back_tv)
    HXTextView backTv;
    @BindView(R.id.title_tv)
    HXTextView titleTv;
    @BindView(R.id.week_form_data)
    RadioButton weekFormData;
    @BindView(R.id.month_form_data)
    RadioButton monthFormData;
    @BindView(R.id.date_rg)
    RadioGroup dateRg;
    @BindView(R.id.search_date_tv)
    HXTextView searchDateTv;
    @BindView(R.id.warning_state_pie_chart)
    PieChart warningStatePieChart;
    @BindView(R.id.equipment_warning_count_bar_chart)
    BarChart equipmentWarningCountBarChart;
    @BindView(R.id.warning_reason_situation_bar_chart)
    BarChart warningReasonSituationBarChart;
    @BindView(R.id.daily_warning_count_line_chart)
    LineChart dailyWarningCountLineChart;

    private BarChartManager equipmentCountBarChartManager,
            reasonSituationBarChartManager;
    private PieChartManager warningStatePieChartManager;
    private LineChartManager dailyCountLineChartManager;
    private String startTime,//开始时间
            endTime;//结束时间（月报表时，为空）
    private boolean selectWeek;
    private Week selectedWeek;
    private Month selectedMonth;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case Constants.FORMDATA_STATUS:
                    EnvironmentFormDataStatistics environmentStateFormData = (EnvironmentFormDataStatistics) msg.obj;
                    if(environmentStateFormData.getxData() == null || environmentStateFormData.getxData().size() <= 0 ||
                            environmentStateFormData.getyData() == null || environmentStateFormData.getyData().size() <= 0 ){
                        warningStatePieChartManager.showNoDataText();
                    }else {
                        warningStatePieChartManager.setPieChart(getXData(environmentStateFormData), getYData(environmentStateFormData.getyData().get(0)), getColors3());
                    }
                    break;
                case Constants.FORMDATA_EQUIPMENT_COUNT:
                    EnvironmentFormDataStatistics equipmentCountFormData = (EnvironmentFormDataStatistics) msg.obj;
                    if(equipmentCountFormData.getxData() == null || equipmentCountFormData.getxData().size() <= 0 ||
                            equipmentCountFormData.getyData() == null || equipmentCountFormData.getyData().size() <= 0 ){
                        equipmentCountBarChartManager.showNoDataText();
                    }else {
                        equipmentCountBarChartManager.showBarChart(equipmentCountFormData.getxData(), getFData(equipmentCountFormData.getyData()),
                                new String[]{"预警", "报警"}, getColors2());
                    }
                    break;
                case Constants.FORMDATA_REASON:
                    EnvironmentFormDataStatistics reasonFormData = (EnvironmentFormDataStatistics) msg.obj;
                    if(reasonFormData.getxData() == null || reasonFormData.getxData().size() <= 0 ||
                            reasonFormData.getyData() == null || reasonFormData.getyData().size() <= 0 ){
                        reasonSituationBarChartManager.showNoDataText();
                    }else {
                        reasonSituationBarChartManager.showBarChart(reasonFormData.getxData(), getFData(reasonFormData.getyData()),
                                new String[]{"预警", "报警"}, getColors2());
                    }
                    break;
                case Constants.FORMDATA_DAILY_COUNT:
                    EnvironmentFormDataStatistics dailyCountFormData = (EnvironmentFormDataStatistics) msg.obj;
                    if(dailyCountFormData.getxData() == null || dailyCountFormData.getxData().size() <= 0 ||
                            dailyCountFormData.getyData() == null || dailyCountFormData.getyData().size() <= 0 ){
                        dailyCountLineChartManager.showNoDataText();
                    }else {
                        dailyCountLineChartManager.showLineChart(dailyCountFormData.getxData(), dailyCountFormData.getyData().get(0), "预警", getResources().getColor(R.color.color_FD9D00));
                        dailyCountLineChartManager.addLine(dailyCountFormData.getyData().get(1), "报警", getResources().getColor(R.color.color_F5573F));
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_environment_form_data);
        ButterKnife.bind(this);
        initWeek();
        initView();
        initData();
    }

    private void initWeek() {
        selectWeek = true;
        selectedWeek = new Week();
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        selectedWeek.setWeekBegin(calendar.getTime());
        startTime = selectedWeek.getWeekBeginDate1();
        calendar.add(Calendar.DAY_OF_MONTH, 6);
        selectedWeek.setWeekEnd(calendar.getTime());
        endTime = selectedWeek.getWeekEndDate1();
        searchDateTv.setText(selectedWeek.getSelectWeekBeginAndEnd());
    }

    private void initMonth() {
        selectWeek = false;
        selectedMonth = new Month();
        Calendar calendar = Calendar.getInstance();
        selectedMonth.setYear(calendar.get(Calendar.YEAR));
        selectedMonth.setMonth(calendar.get(Calendar.MONTH) + 1);
        startTime = selectedMonth.getYearAndMonth1();
        endTime = "";
        searchDateTv.setText(selectedMonth.getYearAndMonth3());
    }

    private void initView() {
        titleTv.setText(R.string.environment_form_data);
        dateRg.setOnCheckedChangeListener(this);

        warningStatePieChartManager = new PieChartManager(warningStatePieChart);
        warningStatePieChartManager.setLegend();
        equipmentCountBarChartManager = new BarChartManager(equipmentWarningCountBarChart);
        equipmentCountBarChartManager.setLegend();
        reasonSituationBarChartManager = new BarChartManager(warningReasonSituationBarChart);
        reasonSituationBarChartManager.setLegend();
        dailyCountLineChartManager = new LineChartManager(dailyWarningCountLineChart);
        dailyCountLineChartManager.setLegend();
    }

    private void initData(){
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                getStatusChartData("搜索中…");
                getEquipmentChartData("搜索中…");
                getReasonChartData("搜索中…");
                getDailyCountChartData("搜索中…");
            }
        }, 500);
    }

    /**
     * 警报状态
     * @param alert
     */
    public void getStatusChartData(String alert) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("constructionId", SPUtil.getString(this, "constructionid"));
            jsonObject.put("startTime", startTime);
            jsonObject.put("endTime", endTime);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, this, "/environmentReport/getAlarmOrWarnFrequency/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    EnvironmentFormDataStatisticsRes res = gson.fromJson(json, EnvironmentFormDataStatisticsRes.class);
                    if(res.getStatus() == 1){
                        Message msg = handler.obtainMessage();
                        msg.what = Constants.FORMDATA_STATUS;
                        msg.obj = res.getValue();
                        msg.sendToTarget();
                    }else{
                        showToast(res.getMsg());
                    }
                }else{
                    showToast("系统异常");
                }
            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    showToast(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    showToast("系统异常");
                }
            }
        });
    }

    /**
     * 各设备警报次数
     * @param alert
     */
    public void getEquipmentChartData(String alert) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("constructionId", SPUtil.getString(this, "constructionid"));
            jsonObject.put("startTime", startTime);
            jsonObject.put("endTime", endTime);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, this, "/environmentReport/getEveryEquipmentAlarmOrWarnFrequency/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    EnvironmentFormDataStatisticsRes res = gson.fromJson(json, EnvironmentFormDataStatisticsRes.class);
                    if(res.getStatus() == 1){
                        Message msg = handler.obtainMessage();
                        msg.what = Constants.FORMDATA_EQUIPMENT_COUNT;
                        msg.obj = res.getValue();
                        msg.sendToTarget();
                    }else{
                        showToast(res.getMsg());
                    }
                }else{
                    showToast("系统异常");
                }
            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    showToast(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    showToast("系统异常");
                }
            }
        });
    }

    /**
     * 警报原因分布情况
     * @param alert
     */
    public void getReasonChartData(String alert) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("constructionId", SPUtil.getString(this, "constructionid"));
            jsonObject.put("startTime", startTime);
            jsonObject.put("endTime", endTime);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, this, "/environmentReport/getAlarmOrWarnReason/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    EnvironmentFormDataStatisticsRes res = gson.fromJson(json, EnvironmentFormDataStatisticsRes.class);
                    if(res.getStatus() == 1){
                        Message msg = handler.obtainMessage();
                        msg.what = Constants.FORMDATA_REASON;
                        msg.obj = res.getValue();
                        msg.sendToTarget();
                    }else{
                        showToast(res.getMsg());
                    }
                }else{
                    showToast("系统异常");
                }
            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    showToast(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    showToast("系统异常");
                }
            }
        });
    }

    /**
     * 每天警报次数
     * @param alert
     */
    public void getDailyCountChartData(String alert) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("constructionId", SPUtil.getString(this, "constructionid"));
            jsonObject.put("startTime", startTime);
            jsonObject.put("endTime", endTime);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, this, "/environmentReport/queryEveryDayAlarmOrWarnFrequency/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    EnvironmentFormDataStatisticsRes res = gson.fromJson(json, EnvironmentFormDataStatisticsRes.class);
                    if(res.getStatus() == 1){
                        Message msg = handler.obtainMessage();
                        msg.what = Constants.FORMDATA_DAILY_COUNT;
                        msg.obj = res.getValue();
                        msg.sendToTarget();
                    }else{
                        showToast(res.getMsg());
                    }
                }else{
                    showToast("系统异常");
                }
            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    showToast(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    showToast("系统异常");
                }
            }
        });
    }

    private List<Integer> getColors2() {
        List<Integer> colors = new ArrayList<>();
        colors.add(getResources().getColor(R.color.color_F5573F));
        colors.add(getResources().getColor(R.color.color_FD9D00));
        return colors;
    }

    private List<Integer> getColors3(){
        List<Integer> colors = new ArrayList<>();
        colors.add(getResources().getColor(R.color.color_EEEEEE));
        colors.add(getResources().getColor(R.color.color_FD9D00));
        colors.add(getResources().getColor(R.color.color_F5573F));
        return colors;
    }

    private List<String> getXData(EnvironmentFormDataStatistics data){
        List<String> xData = new ArrayList<>();
        for (int i = 0; i < data.getxData().size(); i++) {
            String x = data.getxData().get(i) + " " + data.getyData().get(1).get(i) + " " + data.getyData().get(0).get(i) + "次";
            xData.add(x);
        }
        return xData;
    }

    private List<Float> getYData(List<String> data){
        List<Float> yData = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            float y = Float.parseFloat(data.get(i));
            yData.add(y);
        }
        return yData;
    }

    private List<List<Float>> getFData(List<List<String>> data) {
        List<List<Float>> yData = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            List<Float> mData = new ArrayList<>();
            for (int j = 0; j < data.get(i).size(); j++) {
                mData.add(Float.parseFloat(data.get(i).get(j)));
            }
            yData.add(mData);
        }
        return yData;
    }

    @OnClick({R.id.back_tv, R.id.search_date_tv})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_tv:
                finish();
                break;
            case R.id.search_date_tv:
                AlertDialog dialog = null;
                if (selectWeek) {
                    dialog = new WeekPickerDialog(EnvironmentFormDataActivity.this, new WeekPickerDialog.OnWeekSelectListener() {
                        @Override
                        public void onWeekSelect(Week week) {
                            if (week == null) {
                                searchDateTv.setText("请选择");
                            } else {
                                selectedWeek = week;
                                searchDateTv.setText(week.getSelectWeekBeginAndEnd());
                                startTime = week.getWeekBeginDate1();
                                endTime = week.getWeekEndDate1();
                                initData();
                            }
                        }
                    });
                } else {
                    dialog = new MonthPickerDialog(EnvironmentFormDataActivity.this, new MonthPickerDialog.OnMonthSelectListener() {
                        @Override
                        public void onMonthSelect(Month month) {
                            if (month == null) {
                                searchDateTv.setText("请选择");
                            } else {
                                selectedMonth = month;
                                searchDateTv.setText(month.getYearAndMonth2());
                                startTime = month.getYearAndMonth1();
                                endTime = "";
                                initData();
                            }
                        }
                    });
                }
                dialog.getWindow().setGravity(Gravity.BOTTOM);
                dialog.show();
                break;
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (group.getId()) {
            case R.id.date_rg:
                switch (checkedId) {
                    case R.id.week_form_data:
                        initWeek();
                        break;
                    case R.id.month_form_data:
                        initMonth();
                        break;
                }
                break;
        }
        initData();
    }

}
